#!/usr/bin/env python

import pygtk
import sys
import os
pygtk.require('2.0')

import gnomeapplet
import gtk
from datetime import datetime

ifn = "ppp0"
alias = "iPlus"

def ifvalues():
	dev = open("/proc/net/dev", "r").readlines()
	values = {}
	for line in dev[2:]:
		intf = line[:line.index(":")].strip()
		if intf == ifn:
			values[intf] = line[line.index(":") + 1:].split()
			pass
	return values

class RxTxApplet:
	def init(self):
		self.tf = '00:00:00'
		self.tt = '09:00:00'
		self.FMT = '%H:%M:%S'
		if not os.path.isdir(os.path.expanduser('~') + "/.rxtx"):
			os.mkdir(os.path.expanduser('~') + "/.rxtx")
		if not os.path.exists(os.path.expanduser('~') + "/.rxtx/rxtx"):
			open(os.path.expanduser('~') + "/.rxtx/rxtx", "w").write("0;0")
		self.ifn = ifn
		self.alias = alias
		self.srx = long(0)
		self.stx = long(0)
		self.rx = long(0)
		self.tx = long(0)
		self.nsrx = long(0)
		self.nstx = long(0)		
		self.timeout_interval = 1000
		self.timeout_dump_interval = 10000
		self.dispmode = -1
		self.connected = False
	
	def dumprxtx(self):
		if self.connected:
			tc = str(datetime.now().hour) + ":" + str(datetime.now().minute) + ":" + str(datetime.now().second)
			if not (datetime.strptime(tc, self.FMT) > datetime.strptime(self.tf, self.FMT) and datetime.strptime(tc, self.FMT) < datetime.strptime(self.tt, self.FMT)):
				open(os.path.expanduser('~') + "/.rxtx/rxtx", "w").write(str(self.rx + (self.srx-self.nsrx)) + ";" + str(self.tx + (self.stx-self.nstx)))
		return True

	def __init__(self,applet,iid):
		self.init()
		self.button = gtk.Button()
		self.button.set_relief(gtk.RELIEF_NONE)
		self.button.set_label(self.alias + " is down")
		self.button.connect("button_press_event", self.on_button_press_event, applet)
		applet.add(self.button)
		gtk.timeout_add(self.timeout_interval, self.updaterxtx)
		gtk.timeout_add(self.timeout_dump_interval, self.dumprxtx)
		applet.show_all()

	def btoh(self, bytes):
		bytes = float(bytes)
		if bytes >= 1099511627776:
			terabytes = bytes / 1099511627776
			size = '%.2fT' % terabytes
		elif bytes >= 1073741824:
			gigabytes = bytes / 1073741824
			size = '%.2fG' % gigabytes
		elif bytes >= 1048576:
			megabytes = bytes / 1048576
			size = '%.2fM' % megabytes
		elif bytes >= 1024:
			kilobytes = bytes / 1024
			size = '%.2fK' % kilobytes
		else:
			size = '%.2fb' % bytes
		return size

	def updaterxtx(self):
		values = ifvalues()
		if len(values) == 1:
			if not self.connected:
				line = open(os.path.expanduser('~') + "/.rxtx/rxtx", "r").readline().split(";")
				self.rx = long(line[0])
				self.tx = long(line[1])
				self.connected = True
			tc = str(datetime.now().hour) + ":" + str(datetime.now().minute) + ":" + str(datetime.now().second)
			if datetime.strptime(tc, self.FMT) > datetime.strptime(self.tf, self.FMT) and datetime.strptime(tc, self.FMT) < datetime.strptime(self.tt, self.FMT):
				self.nsrx = long(values[self.ifn][0]) - self.srx
				self.nstx = long(values[self.ifn][8]) - self.stx
				if self.dispmode == -1:
					self.button.set_label("nrx:" + self.btoh(self.nsrx) + " ntx:"  +  self.btoh(self.nstx))
				if self.dispmode == 1:
					self.button.set_label(self.alias + " is up")
				return True

			self.srx = long(values[self.ifn][0])
			self.stx = long(values[self.ifn][8])
			if self.dispmode == -1:
				self.button.set_label("rx:" + self.btoh((self.srx-self.nsrx)+self.rx) + " tx:"  +  self.btoh((self.stx-self.nstx)+self.tx))
			if self.dispmode == 1:
				self.button.set_label(self.alias + " is up")
		else:
			self.dumprxtx()
			self.connected = False
			self.button.set_label(self.alias + " is down" )
			self.rx = self.tx = self.srx = self.stx = self.nsrx = self.nstx = 0
	    
		return True

	def on_button_press_event(self,widget, event, applet):
		if event.type == gtk.gdk.BUTTON_PRESS and event.button == 3:
			widget.emit_stop_by_name("button_press_event")
		if event.type == gtk.gdk.BUTTON_PRESS and event.button == 1:
			self.dispmode = self.dispmode * -1
			self.updaterxtx()

def factory(applet, iid):
	RxTxApplet(applet, iid)
	return True


if __name__ == '__main__':
	gnomeapplet.bonobo_factory("OAFIID:GNOME_RxTx_Factory", gnomeapplet.Applet.__gtype__, "RxTx Applet", "0.1", factory)


